package com.huaxia.day16;

import com.huaxia.day11.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class CharIOTest {

    public static void main(String[] args) throws Exception {
        rwTxt();
        rwLoadTxt();
    }


    public static void rwTxt() {
        List<Student> students = new ArrayList<Student>();
        String fileName = "D:\\develop\\workspace\\huaxia\\huaxia\\doc\\student.txt";
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                Student student = new Student();
                student.setName(line.split(" ")[0]);
                student.setAge(Integer.valueOf(line.split(" ")[1]));
                students.add(student);
                System.out.println(student.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void rwLoadTxt() {
        List<Student> students = new ArrayList<Student>();
        String fileRead = "D:\\develop\\workspace\\huaxia\\huaxia\\doc\\student.txt";
        String fileWrite = "D:\\develop\\workspace\\huaxia\\huaxia\\doc\\student_write.txt";

        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fileRead), "UTF-8"));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileWrite), "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] lineContent = line.split(" ");
                Student student = new Student();
                student.setName(lineContent[0]);
                student.setAge(Integer.valueOf(lineContent[1]));
                students.add(student);
                System.out.println(student.toString());
                bw.write(lineContent[1] + "," + lineContent[0]);
                bw.newLine();
                /*
                不同系统的换行符：
                windows -->   \r\n
                linux   -->   \r
                mac     -->   \n
                File.separator 处理系统兼容问题
                */
            }
            bw.flush();//刷缓存
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
